package com.example.fbi_text.views;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;


import com.example.fbi_text.Acitivity.ChangeTextActivity;
import com.example.fbi_text.Acitivity.MainNewsActivity;
import com.example.fbi_text.Acitivity.PriticularsActivity;
import com.example.fbi_text.R;


import com.example.fbi_text.adapter.NewsAdapter;
import com.example.fbi_text.base.BaseFragment;
import com.example.fbi_text.bean.News;
import com.example.fbi_text.database.DBHelper;
import com.example.fbi_text.utils.SpUtils;

import java.util.ArrayList;
import java.util.List;

public class Mainfragment extends BaseFragment implements MainNewsActivity.OnNewsUpdateListener{
private HeaderView mheaderview;
private Mainitem01View mainitem01View;
private Mainitem02View mainitem02View;
private SpUtils msputils;
private List<News> mNews;
private NewsAdapter mNewsAdapter;

private ListView mLVNews;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main;
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void initView() {
        mheaderview = mView.findViewById(R.id.main_header);
        mainitem01View = mView.findViewById(R.id.Mainitem01);
        mainitem02View = mView.findViewById(R.id.Mainitem02);
        mLVNews = mView.findViewById(R.id.main_item01_listview);
//        msputils =new SpUtils(mContext);

        mheaderview.setTitle("111");
//        顶部图片的显示隐藏
        mheaderview.setImageVisibility(View.VISIBLE);

//        顶部文字的显示隐藏
        mheaderview.setTitleVisibility(View.GONE);

//        顶部搜索栏的显示隐藏
        mheaderview.setSerchViewVisibility(View.VISIBLE);
        //隐藏返回按钮
      mheaderview.setmHeaderBackVisibility(View.INVISIBLE);

        refreshNewsList();

//        News news = new News();
        //从库中提出数据显示
        mNews = DBHelper.getInstance(mContext).selectAllNews();
        mNewsAdapter = new NewsAdapter(mNews,mContext);
        mLVNews.setAdapter(mNewsAdapter);

        mLVNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                News news = (News) view.getTag(R.integer.news_tag);
                Intent intent = new Intent(view.getContext(), PriticularsActivity.class);
                String a = String.valueOf(news.getNews_id());
                intent.putExtra("id",a);
                view.getContext().startActivity(intent);
                Log.d("TAG", "onItemClick: "+news.getNews_id());
            }
        });

        // 设置新闻更新监听器
        if (getActivity() instanceof MainNewsActivity) {
            ((MainNewsActivity) getActivity()).setOnNewsUpdateListener(this);
        }


        // 设置搜索监听
        mheaderview.setOnSearchListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 用户提交搜索时触发
                filterNews(query);
                return true;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                // 输入内容实时变化时触发
                filterNews(newText);
                return true;
            }
        });
//    //   短按修改news_title
//        mLVNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                News news = (News) view.getTag(R.integer.news_tag);
//                DBHelper.getInstance(mContext).updateNewsNameById(news.getNews_title() + "s", news.getNews_id());
//                refreshNewsList();
//            }
//        });
//        //长按学生列表的条目
//        mLVNews.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                News news = (News) view.getTag(R.integer.news_tag);
//                //弹框提示是否删除
//                showDeleteDialog(news);
//                return true;
//            }
//
//        });
//
//        mainitem02View.setmtitle02("22222");
//        mainitem02View.setmauthor02("222222222");
//        mainitem02View.setmcontent02("23232323232");
//        mainitem02View.setmImageSrc("@mipmap/setting");


    }

//    //系统弹框
//    private void showDeleteDialog(News news) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//        builder.setTitle("删除");
//        builder.setMessage("确定要删除吗？");
//        builder.setIcon(R.mipmap.attention);
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//
//            }
//        });
//        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                DBHelper.getInstance(mContext).deleteNewsById(news.getNews_id());
//                showToast(news.getNews_content() + "信息被删除");
//                refreshNewsList();
//            }
//        });
//        Dialog dialog = builder.create();
//        dialog.show();
//
//    }
//
//    //刷新列表：重新去数据库中查询数据，并将数据设置到Adapter中。
//    public void refreshNewsList() {
//        mNews = DBHelper.getInstance(mContext).selectAllNews();
//        mNewsAdapter.updateData(mNews);
//    }

    // 筛选新闻方法
    private void filterNews(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            // 如果关键字为空，显示全部新闻
            refreshNewsList();
            return;
        }
        // 从数据库获取所有新闻
        List<News> allNews = DBHelper.getInstance(mContext).selectAllNews();
        List<News> filteredNews = new ArrayList<>();

        // 筛选标题或内容包含关键字的新闻（不区分大小写）
        for (News news : allNews) {
            if (news.getNews_title().toLowerCase().contains(keyword.toLowerCase()) ||
                    news.getNews_content().toLowerCase().contains(keyword.toLowerCase())||
                    news.getNews_author().toLowerCase().contains(keyword.toLowerCase())||
                    news.getNews_time().toLowerCase().contains(keyword.toLowerCase())){
                filteredNews.add(news);
            }
        }

        // 更新Adapter
        if (mNewsAdapter == null) {
            mNewsAdapter = new NewsAdapter(filteredNews, mContext);
            mLVNews.setAdapter(mNewsAdapter);
        } else {
            mNewsAdapter.updateData(filteredNews);
        }
    }

    // 实现OnNewsUpdateListener接口
    @Override
    public void onNewsUpdated() {
        // 当新闻更新时刷新列表
        refreshNewsList();
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d("MainFragment", "设置更新监听器");
        // 设置更新监听器
        ChangeTextActivity.setOnNewsUpdateListener(new ChangeTextActivity.OnNewsUpdateListener() {
            @Override
            public void onNewsUpdated() {
                Log.d("MainFragment", "收到更新回调");
                requireActivity().runOnUiThread(() -> {
                    refreshNewsList();
                    Log.d("MainFragment", "列表刷新完成");
                });
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("MainFragment", "移除更新监听器");
        // 移除监听器防止内存泄漏
        ChangeTextActivity.removeOnNewsUpdateListener();
    }
    // 刷新列表方法
    private void refreshNewsList() {
        Log.d("MainFragment", "开始刷新列表");
        if (getActivity() == null || getActivity().isFinishing()) {
            Log.e("MainFragment", "Activity不可用，取消刷新");
            return;
        }

        try {
            List<News> newData = DBHelper.getInstance(mContext).selectAllNews();
            Log.d("MainFragment", "查询到" + newData.size() + "条数据");

            if (mNewsAdapter == null) {
                mNewsAdapter = new NewsAdapter(newData, mContext);
                mLVNews.setAdapter(mNewsAdapter);
            } else {
                mNewsAdapter.updateData(newData);
                // 确保调用notifyDataSetChanged
                mNewsAdapter.notifyDataSetChanged();
            }
            Log.d("MainFragment", "列表刷新完成");
        } catch (Exception e) {
            Log.e("MainFragment", "刷新列表出错", e);
        }
    }
    @Override
    protected void initListener() {

    }

    private void ShowNewsList(){

    }
}
